/*
 * FileExporter.java
 *
 * Copyright (C) 2005-2007 Tommi Laukkanen
 * http://www.substanceofcode.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

package com.substanceofcode.carmanager.model;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

/**
 * FileExporter is used when user wants to export fill-up entries to CSV file.
 *
 * @author Tommi Laukkanen
 */
public class FileExporter {
    
    /** Creates a new instance of FileExporter */
    public FileExporter() {
    }
    
    /** Export fillup entries to specified path using the File Connection API */
    public void export(Vector fillupEntries, String path) throws IOException {
        FileConnection connection;
        try {
            connection = (FileConnection)
            Connector.open("file:///" + path, Connector.WRITE );
        } catch(Exception ex) {
            throw new IOException("writeToFile: Open Connector: " + ex.toString());
        }
        
        try{
            // Create file
            connection.create();
        } catch(Exception ex) {
            throw new IOException("writeToFile: Check and create: " + ex.toString());
        }
        
        // Create output stream and write data;
        OutputStream out;
        try{
            out = connection.openOutputStream();
        } catch(Exception ex) {
            throw new IOException("writeToFile: Open output stream: " + ex.toString());
        }
        PrintStream output = new PrintStream( out );
        
        // Create CSV content
        String csvData = createCsv(fillupEntries);
                
        // Write file and close streams
        output.println( csvData );
        output.close();
        out.close();
        connection.close();        
    }

    /** Create CSV content */
    private String createCsv(Vector fillupEntries) {
        String csv = "\"Date\";\"Fill-up\";\"Mileage\";\"Full Fill-up\";" +
                "\"Total Price\";\"Price per liter\";\"Comment\"\r\n";
        Enumeration fillupEnum = fillupEntries.elements();
        while( fillupEnum.hasMoreElements() ) {
            FillupEntry entry = (FillupEntry) fillupEnum.nextElement();
            csv += "\"" + entry.getTime().toString() + "\";\"";
            csv += getDecimalString( entry.getGas(), 2) + "\";\"";
            csv += entry.getKm() + "\";\"";
            csv += entry.getFullFillUp() + "\";\"";
            csv += getDecimalString( entry.getPrice(), 2) + "\";\"";
            csv += getDecimalString( entry.getPricePerLiter(), 3) + "\";\"";
            csv += entry.getComment();
            csv += "\"\r\n";
        }
        return csv;
    }
    
    private String getDecimalString(long value, int decimalCount) {
        String number = Long.toString(value);
        String cents = "00";
        String normal = "0";
        int len;
        len = number.length();
        if( len>2 ) {
            cents = number.substring(len-decimalCount, len);
            normal = number.substring(0, len-decimalCount);
        }
        if( len==2 ) {
            cents = number;
        }
        if( len==1 ) {
            cents = "0" + number;
        }
        return normal + "." + cents;
    }
    
}
